'use strict'
const fs = require('fs');

class sticker {

    constructor() {
        this.param = '/:id'
    }
    //创建资源
    async get(c) {
        try {
            var openid = c.box.user.openid;
            var sticker_id = c.param.id;
            const sqltext1 = `select * from users where openid = '${openid}'`
            var r1 = await c.service.psql.query(sqltext1);
            var user_id = r1.rows[0].user_id;
            var wela = r1.rows[0].user_coin;

            // 查找template coin
            var isPay = await c.service.psql.query(`select * from user_${user_id}_pay_sti where sticker_id = ${sticker_id}`);
            if(isPay.rowCount>0){
                return c.send('您已经有啦！')
            }

            let sqltext2 = `select sticker_pay`
                + ` from sticker `
                + ` where sticker_id = ${sticker_id}`
            var r2 = await c.service.psql.query(sqltext2)
            if (r2.rowCount === 0) {
                return c.status(404).send('sticker not found')
            }
            var coin = r2.rows[0].sticker_pay;

            if (coin > wela) {
                return c.send("coin don't enough");
            }
            else {
                var now_coin = wela - coin;

                let sqltext3 = `UPDATE users SET user_coin = ${now_coin} where openid = '${openid}';
                insert into user_${user_id}_pay_sti (user_id,openid,sticker_id) values(${user_id},'${openid}',${sticker_id})`
                let r3 = await c.service.psql.query(sqltext3);
                return c.send({
                    result:'success',
                    now_coin: now_coin
                });
            }
        } catch (err) {
            console.log(err);
            return c.status(500).send('err');
        }
    }
}


module.exports = sticker
